//
//  DSFMovieDetailFFMDBModel.m
//  TVFan3.0
//
//  Created by 姬鑫宇 on 15/3/13.
//  Copyright (c) 2015年 李胜男. All rights reserved.
//

#define DataBaseName @"movieInfo.sqlite"

#import "DSFMovieDetailFFMDBModel.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

static DSFMovieDetailFFMDBModel *sharedSingleton = nil;

@implementation DSFMovieDetailFFMDBModel
{
    FMDatabase  *db;
    FMDatabaseQueue *queue;
} 

+(DSFMovieDetailFFMDBModel *)sharedSingleton{
    @synchronized(self)
    {
        if (!sharedSingleton)
        {
            sharedSingleton = [[DSFMovieDetailFFMDBModel alloc] init];
        }
        
    }
    
    return sharedSingleton;
}

-(NSString *)databaseFilePath{
    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [filePath objectAtIndex:0];
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:DataBaseName];
    return dbFilePath;
}

-(void)createDataBase
{
    db = [FMDatabase databaseWithPath:[self databaseFilePath]];
}

-(void)createTable{
    if (!db) {
        [self createDataBase];
    }
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    //为数据库设置缓存，提高查询效率
    [db setShouldCacheStatements:YES];
    if (![self isTableOK]) {
        //判断数据库中是否已经存在这个表，如果不存在则创建该表
        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS HistoryList (ID INTEGER PRIMARY KEY AUTOINCREMENT, ChartId INTEGER, ChartCount INTEGER)"];
        if(result){
            NSLog(@"创建完成");
        }else
            NSLog(@"创建失败");
    }
}

- (BOOL) isTableOK
{
    FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from HistoryList"];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
       // NSLog(@"isTableOK %ld", count);
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    return NO;
}

-(void)insertHistory:(NSInteger )chartId
          chartCount:(NSInteger)chartCount
{
    if (!db) {
        [self createDataBase];
    }
    
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    
    [db setShouldCacheStatements:YES];
    
    if(![self isTableOK])
    {
        [self createTable];
    }
    //以上操作与创建表是做的判断逻辑相同
    //现在表中查询有没有相同的元素，如果有，做修改操作
    
    FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"select * from HistoryList where ChartId = '%ld'",(long)chartId]];
    if([rs next])
    {
        [db executeUpdate:[NSString stringWithFormat:@"delete from HistoryList where ChartId = '%ld'", (long)chartId]];
    }
    //去重，重新插入
    BOOL result = [db executeUpdate:[NSString stringWithFormat:@"INSERT INTO HistoryList(ChartId, ChartCount) VALUES('%ld','%ld')",(long)chartId,(long)chartCount]];
    if(result){
        NSLog(@"添加成功");
    }else
        NSLog(@"添加失败");
}
//删除数据
-(void)deleteChartId:(NSInteger)chartId
{
    if (!db) {
        [self createDataBase];
    }
    
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    
    [db setShouldCacheStatements:YES];
    //判断表中是否有指定的数据， 如果没有则无删除的必要，直接return
    if(![self isTableOK])
    {
        return;
    }
    //删除操作
    [db executeUpdate:[NSString stringWithFormat:@"delete from HistoryList where ChartId = '%ld'", (long)chartId]];

    [db close];
}
//修改操作与增加操作的步骤一致
//查询
-(NSInteger)getCountByChartId:(NSInteger)chartId{
    if (!db) {
        [self createDataBase];
    }
    
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return 0;
    }
    
    [db setShouldCacheStatements:YES];
    
    if(![self isTableOK])
    {
        return 0;
    }
    
    FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"select * from HistoryList where ChartId = '%ld'",(long)chartId]];
    if ([rs next]) {
        return [rs intForColumn:@"ChartCount"];
    }else
        return 0;
}

@end
